import {getRequest} from "./api";
import Home from '../views/Home'

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return
    }
    getRequest(store.state.loginServiceApi + '/system/menu').then(res => {
        if (res.code == 200){
            if (res.data) {
                // 格式化好的数据
                let fmtRoutes = formatRoutes(res.data)
                // 添加到路由
                router.addRoutes(fmtRoutes)
                // 将数据存入vuex
                store.commit('initRoutes', fmtRoutes)
            }
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = []
    routes.forEach(item => {
        let {
            id,
            path,
            component,
            name,
            iconCls,
            children,
        } = item
        if (children && children instanceof Array) {
            // 递归
            children = formatRoutes(children)
        }
        let fmRouter = {
            id:id,
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            // 懒加载路由
            component(resolve) {
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith('Personal')) {
                    require(['../views/personal/' + component + '.vue'], resolve)
                }  else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter)
    })
    return fmtRoutes
}
